<template>
  <div class="game-page">
    <div class="top">
      <div class="title">
        <div class="link">
          <router-link to="/">首页</router-link>
          <router-link :to="`/editor/${$route.params.gameId}`">编辑</router-link>
        </div>
        <div>
          当前关卡 —— {{ map.name }}
        </div>
        <div>
          难度 —— {{ map.difficulty }}
        </div>
      </div>
      <div class="score"><span style="color: black; font-size: 22px;">分数：</span>{{ score }}</div>
    </div>
    <div class="game-panel">
      <canvas id="snake-game" ref="game" :width="width" :height="height"></canvas>
    </div>
    <div class="setting">
      <div class="control">
        <button id="new-game" @click="newGame">新游戏</button>
      </div>
      <div>
        上下左右 方向键控制移动，Q键加速，E键减速
      </div>
    </div>
  </div>
</template>

<script>
import Game from '@/scripts/game'
import { drawLoading } from '@/scripts/graphics'
import { WINDOW_HEIGHT, WINDOW_WIDTH } from '@/scripts/args'
import { get } from '@/scripts/http'

export default {
  name: 'Game',
  data () {
    return {
      width: WINDOW_WIDTH,
      height: WINDOW_HEIGHT,
      game: undefined,
      score: 0,
      name: '',
      difficulty: '',
      map: {}
    }
  },
  methods: {
    newGame () {
      this.game?.abort()
      const canvas = this.$refs['game']
      const context = canvas.getContext('2d')
      drawLoading(context)

      this.game = new Game(context, this.map)
      this.score = 0
      const game = this.game
      game.bindScoreChangeEvent((score) => {
        this.score = score
      })
      game.init()
      setTimeout(() => game.start(), 3000)
    },
  },
  async mounted () {
    this.map = await get(`/api/maps/${this.$route.params.gameId}`)
  }
}
</script>

<style scoped>
.game-panel {
  padding: 20px;
  border: 1px solid #000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.setting {
  margin: 20px;
}

.control {

}

.control #new-game {
  width: 200px;
  height: 50px;
  background-color: rgba(255, 0, 0, .4);
  color: white;
  font-size: 18px;
  border: 3px solid greenyellow;
  outline: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 25px;
}

#new-game:hover {
  cursor: pointer;
  background-color: skyblue;
}

.game-page {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  flex-direction: column;
  width: 620px;
}

.top {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: flex-end;
  width: 100%;
}

.title {

}

.score {
  color: red;
  font-size: 32px;
}

.link a {
  margin-right: 20px;
}
</style>